#-*-coding:utf-8-*-
import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import db
import weather
import emailInfo
import RPi.GPIO as GPIO  
import time
import subprocess

# init button
cnt = 3
timing = False
def button_pressed(key):
    global cnt
    cnt = (cnt+1)%4
    global timing
    timing = False
    print("button pressed!"+str(cnt))
GPIO.setwarnings(False) 
GPIO.setmode(GPIO.BCM) 
KEY = 18   
GPIO.setup(KEY,GPIO.IN) 
GPIO.add_event_detect(KEY, GPIO.RISING, callback=button_pressed,bouncetime=200)

# init oled
RST = None
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
disp.begin()
disp.clear()
disp.display()

# init draw
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
draw = ImageDraw.Draw(image)
# Draw a black filled box to clear the image.
draw.rectangle((0,0,width,height), outline=0, fill=0)

# init position
padding = -2
top = padding
bottom = height-padding
x = 0
size = 16
font = ImageFont.truetype('MSYHBD.TTC', size - 2)
course_shown = False
def show_course():
    y = top
    # draw.text((x, y),"课程表",  font=font, fill=255)
    result = db.get_course()
    print(result)
    if len(result) == 0:
        draw.text((x, y),"今日无课",  font=font, fill=255)
    for course in result:
        draw.text((x, y),course['name'],  font=font, fill=255)
        draw.text((x+size*4, y),course['location'],  font=font, fill=255)
        y += size
        draw.text((x, y),course['time'],  font=font, fill=255)
        y += size

def show_weather():
    result = weather.get_weather()
    now_weather = result['hourly'][0]['weather']
    img_idx = result['hourly'][0]['img']
    week_idx = result['week']
    path = "./weathercn/"+img_idx+".png"
    show_img(path,0,0)
    draw.text((x+15, top+50),result['city'],  font=font, fill=255)
    draw.text((x+64, top),week_idx,  font=font, fill=255)
    draw.text((x+64, top+size),now_weather,  font=font, fill=255)
    draw.text((x+64+size*2, top+size),result['temp']+"℃",  font=font, fill=255)
    draw.text((x+64, top+size*2),result['templow'] + "~" + result['temphigh'] + "℃",  font=font, fill=255)
    draw.text((x+64, top+size*3),"明天:"+result['daily'][1]['day']['weather'],  font=font, fill=255)

def show_img(path,dx,dy):
    w_img = Image.open(path).resize((50,50),Image.BOX).convert('1')
    draw.bitmap((x+dx, top+dy),w_img,fill=255)

def show_email():
    info = emailInfo.get_mail()
    email_count = info['count']
    subjects = info['subjects']
    if email_count == 0:
        draw.text((x, top),"暂无邮件未读",  font=font, fill=255)
        return 
    draw.text((x, top),"有"+str(email_count)+"封邮件未读",  font=font, fill=255)
    for i in range(email_count):
        if i > 2:
            break
        if len(subjects[i]) > 13:
            draw.text((x, top+size*(i+1)),subjects[i][0:13] + " ...",  font=font, fill=255)
        else:
            draw.text((x, top+size*(i+1)),subjects[i],  font=font, fill=255)

    


weather_shown = False
email_shown = False
try:
    while True:
        disp.image(image)
        disp.display()
        time.sleep(.1)
        
        if cnt == 0:
            if not weather_shown:
                draw.rectangle((0,0,width,height), outline=0, fill=0)
                course_shown = False
                email_shown = False
                show_weather()
                weather_shown = True
        elif cnt == 1:
            if not course_shown:
                draw.rectangle((0,0,width,height), outline=0, fill=0)
                weather_shown = False
                email_shown = False
                show_course()
                course_shown = True
        elif cnt ==2:
            if not email_shown:
                course_shown = False
                weather_shown = False
                draw.rectangle((0,0,width,height), outline=0, fill=0)
                show_email()
                email_shown = True
        elif cnt == 3:
            timing = True
            # print(timing)
            while timing == True:
                draw.rectangle((0,0,width,height), outline=0, fill=0)
                local = time.localtime()
                # print(local)
                day = time.strftime("%Y-%m-%d", local)
                cur = time.strftime("%H:%M:%S", local)
                draw.text((x+15, top),day, font=ImageFont.truetype('MSYHBD.TTC', 17), fill=255)
                draw.text((x+18, top+15),cur, font=ImageFont.truetype('MSYHBD.TTC', 20), fill=255)
                # show ip
                default_font = ImageFont.load_default()
                cmd = "hostname -I | cut -d\' \' -f1"
                IP = subprocess.check_output(cmd, shell = True )
                draw.text((x, top+45),"IP: " + str(IP.decode()),  font=default_font, fill=255)
                # show cpu
                cmd = "top -bn1 | grep load | awk '{printf \"CPU Load: %.2f\", $(NF-2)}'"
                CPU = subprocess.check_output(cmd, shell = True )
                draw.text((x, top+53),str(CPU.decode()),  font=default_font, fill=255)
                
                disp.image(image)
                disp.display()
        
finally:
    draw.rectangle((0,0,width,height), outline=0, fill=0)
    disp.image(image)
    disp.display()
    
